<?php

namespace app\stores\logic\order;

use app\beautiful\logic\FreightLogic;

use app\beautiful\model\goods\GoodsGroupModel;
use app\beautiful\model\goods\GoodsOtherSkuDetailModel;
use app\beautiful\model\mall\FlashSaleGoodsModel;

use app\beautiful\model\mall\FlashSaleGoodsSkuModel;

use app\beautiful\model\mall\FreightTemplateModel;
use app\beautiful\model\mall\GoodsCategoryModel;
use app\beautiful\model\mall\GoodsModel;

use app\beautiful\model\mall\GoodsSkuModel;

use app\beautiful\model\mall\PinTuanGoodsModel;
use app\beautiful\model\member\MemberCouponModel;

use app\beautiful\model\order\GoodsOrderItemModel;

use app\beautiful\model\order\GoodsOrderModel;

use app\beautiful\model\order\OrderGoodsGroupDetailModel;
use app\beautiful\model\order\OrderGoodsGroupModel;
use app\beautiful\model\order\OrderGoodsModel;
use app\beautiful\model\setting\SettingBalanceModel;

use app\beautiful\model\setting\SettingIntegralModel;



class OrderFlashSaleLogic{

    use OrderTrait;

    protected $flash_sale_goods_data=[];

    protected $total_price=0;

    protected $member_coupon_id;

    protected $flash_sale_sku_datas=[];

    protected $order_item_data=[];

    protected $order_goods_data=[];

    protected $num;

    protected $shopId;

    protected $goods;

    protected $member_id;

    protected $all_goods_gross;

    public function createOrder($params)

    {



        //判断用户

        empty($params['member_id']) && $this->error('请先登录后再操作');

        $this->checkMember($params['member_id'], false);

        $this->member_id = $params['member_id'];

        //判断商品、限购、限量

        if(empty($params['goods']) || !is_array($params))  $this->error('请选择商品');

        foreach ($params['goods'] as $k => $v){

            $this->checkGoods($v,false);

        }



        //判断配送方式

        if(!in_array($params['logistics_type'],[0,1,2,3])) $this->error('请选择配送方式');

        //快速配送判断邮寄地址

        if($params['logistics_type']==1){

            empty($params['receiving_name']) && $this->error('请输入收货人');

            if(empty($params['receiving_mobile']) || (!is_mobile($params['receiving_mobile']) && !is_phone($params['receiving_mobile'])))  $this->error('请输入收货人手机号');

            empty($params['receiving_address_province']) && $this->error('请输入收货省份');

            empty($params['receiving_address_city']) && $this->error('请输入收货城市');

            empty($params['receiving_address_county']) && $this->error('请输入收货城镇');

            empty($params['receiving_address_info']) && $this->error('请输入收货具体地址');

        }



        //判断总价

        if(empty($params['total_price'])) $this->error('参数错误#1');

        if((float)$params['total_price'] != $this->total_price) $this->error('参数错误#2');



        //判断优惠卷

        $coupon_id = $params['coupon_id'] ?? 0;

        $couponBalance = 0;

        if(!empty($coupon_id)){

            if(null === $myCoupon =  MemberCouponModel::find($coupon_id)) $this->error('优惠券不存在');

            if($myCoupon->status == 1 || $myCoupon->money_limit > $this->total_price) $this->error('该优惠券不可用');

            if($myCoupon->member_id != $params['member_id'])  $this->error('该优惠券不可用');

            $couponBalance = $myCoupon->coupon_money;

        }



        //判断积分抵扣

        $use_integral=(int)$params['use_integral'];

        if($use_integral==1){

            $integral_balance=$this->getIntegralBalance($this->total_price);

        }

        $integral=isset($integral_balance) ? $integral_balance['integral'] : 0;

        $balance=isset($integral_balance) ? $integral_balance['balance'] : 0;





        //获取邮费

        $freight = 0;

        if($params['logistics_type']==1){

            $province= empty($params['receiving_address_province']) ? '' : $params['receiving_address_province'];

            $freight_logic= new FreightLogic($this->shopId);

            $freight=$freight_logic->getFreightPrice($province,$this->num);

            if($freight==-1) $this->error('收货地址暂不支持发货');

        }



        //获取需要支付的金额

        $need_pay=round((($this->total_price)*100 + $freight*100 - $couponBalance*100 - $balance*100)/100,2);

        //判断支付方式
        $return = checkPayWay($params,$need_pay,$this->member->member_id,$this->shopId);

        if($return['error']){
            $this->error($return['error']);
        }else{
            $mix_pay_money = $return['mix_pay_money'];
        }

        //保存订单

        $order = new GoodsOrderModel();

        $order_data=[

            'shop_id'=>$this->shopId,

            'order_type'=>'flash_sale',

            'logistics_type'=>$params['logistics_type'],

            'member_id'=>$params['member_id'],

            'total_price'=>$this->total_price,

            'need_pay'=>$need_pay,

            'freight'=>$freight,

            'member_coupon_id'=>$params['coupon_id'],

            'coupon_money'=>$couponBalance,

            'use_integral'=>isset($integral_balance) ? $integral_balance['integral'] : 0,

            'integral_balance'=>isset($integral_balance) ? $integral_balance['balance'] : 0,

            'is_paid'=>0,

            'status'=>1,

            'from_type'=>$params['from_type'],

            'order_send_time'=>$params['order_send_time']?json_encode($params['order_send_time']):$params['order_send_time'],

            'all_goods_gross'=>$this->all_goods_gross,

            'mix_pay_type'=>(isset($mix_pay_money) && $mix_pay_money)?implode(',',array_keys($mix_pay_money)):null,

            'platform_money'=>isset($mix_pay_money['platform_money'])?$mix_pay_money['platform_money']:0,

            'money'=>isset($mix_pay_money['money'])?$mix_pay_money['money']:0,

            'weixin'=>isset($mix_pay_money['weixin'])?$mix_pay_money['weixin']:0

        ];

        if($params['logistics_type']==1){

            $order_data['receiving_name']=$params['receiving_name'];

            $order_data['receiving_mobile']=$params['receiving_mobile'];

            $order_data['receiving_address_province']=$params['receiving_address_province'];

            $order_data['receiving_address_city']=$params['receiving_address_city'];

            $order_data['receiving_address_county']=$params['receiving_address_county'];

            $order_data['receiving_address_info']=$params['receiving_address_info'];

            if($params['logistics_type']==1){

                $ft = FreightTemplateModel::where(['shop_id'=>$this->shopId])->find();

                $order_data['hours']=$ft->hours;

                $order_data['freight_type']=$ft->freight_type;
            }

        }

        $order->save($order_data);

        GoodsOrderModel::where(['order_id'=>$order->order_id])->save(['order_sn'=>createOrderSn($order->order_id,4)]);

        //保存订单商品
        $order_item_model= new GoodsOrderItemModel();

        foreach ($this->order_item_data as $k => $v){
            $v['order_id']=$order->order_id;
            $order_item_id = $order_item_model->insertGetId($v);

            $this->order_goods_data[$k]['order_id']=$order->order_id;
            $this->order_goods_data[$k]['order_item_id']=$order_item_id;
        }
        $order_goods_model= new OrderGoodsModel();
        $order_goods_model->saveAll($this->order_goods_data);

//        $order_item_model->saveAll($this->order_item_data);


        //保存秒杀商品

        $flash_sale_goods_model=new FlashSaleGoodsModel();

        $flash_sale_goods_model->saveAll($this->flash_sale_goods_data);



        //保存商品规格

        $flash_sale_goods_sku_model = new FlashSaleGoodsSkuModel();

        $flash_sale_goods_sku_model->saveAll($this->flash_sale_sku_datas);

        if($this->goods->type==3){
            //创建订单套餐分组和分组详情
            $flash_sale_goods = FlashSaleGoodsModel::with(['goods'])->where(['flash_sale_goods_id'=>$this->flash_sale_goods_id])->find();

            if(!$flash_sale_goods) return $this->error('数据有误');
            $flash_sale_goods = $flash_sale_goods->toArray();

            $order_item = GoodsOrderItemModel::where(['order_id'=>$order->order_id])->find();
            $this->goodsGroup($flash_sale_goods['goods'],$order->order_id,$order_item->order_item_id);
            $this->goods($flash_sale_goods['goods'],$order->order_id,$order_item->order_item_id);
            //套餐订单分组详情
            $order_group_detail = new OrderGoodsGroupDetailModel();
            $order_group_detail->saveAll($this->order_goods_group_detail);
        }

        return $order->order_id;

    }

    protected function goodsGroup($datas,$order_id,$order_item_id){
        empty($datas['goods_id']) && $this->error('参数错误#');

        $goods_group = GoodsGroupModel::with(['groupDetail'=>function($query){
            $query->with(['goods'=>function($query){
                $query->where(['is_delete'=>0]);
            }])->where(['is_delete'=>0]);
        }])->where([
            ['shop_id','=',$this->shopId],
            ['is_delete','=',0],
            ['goods_id','=',$datas['goods_id']]
        ])->field('*')
            ->select()->toArray();

        if($goods_group){
            $group_model = new OrderGoodsGroupModel();
            foreach ($goods_group as $k=>$v){
                $order_goods_group = [
                    'shop_id' => $v['shop_id'],
                    'order_id'=>$order_id,
                    'order_item_id'=>$order_item_id,
                    'goods_id' => $v['goods_id'],
                    'group_name' => $v['group_name'],
                    'type' => $v['type'],
                    'num' => $v['num'],
                    'choose_num' => $v['choose_num'],
                    'is_choose_same' => $v['is_choose_same']
                ];
                $group_model->save($order_goods_group);

                $this->goodGroupDetail($v['groupDetail'],$group_model->order_goods_group_id,$order_id,$order_item_id);

                $this->order_goods_group_id[] = $group_model->order_goods_group_id;
            }

        }


    }

    protected function goodGroupDetail($datas,$order_goods_group_id,$order_id,$order_item_id){
        if($datas){

            foreach ($datas as $k=>$v){
                $detail['shop_id'] = $v['shop_id'];
                $detail['order_id'] = $order_id;
                $detail['order_item_id'] = $order_item_id;
                $detail['order_goods_group_id'] = $order_goods_group_id;
                $detail['num'] = $v['num'];
                $detail['use_condition'] = $v['use_condition'];
                $detail['once_limit_num'] = $v['once_limit_num'];
                $detail['end_type'] = $v['end_type'];
                $detail['end_time_num'] = $v['end_time_num'];
                $detail['end_time_type'] = $v['end_time_type'];
                $detail['sort'] = $v['sort'];
                $detail['remain_num'] = $v['num'];
                $detail['goods_group_detail_id'] = $v['goods_group_detail_id'];
                if($v['goods_id']){
                    $unit = GoodsOtherSkuDetailModel::where(['is_delete'=>0,'other_sku_detail_id'=>$v['goods']['unit_id']])->find();
                    $sku = GoodsSkuModel::where(['goods_id'=>$v['goods_id'],'sku_id'=>$v['sku_id'],'is_delete'=>0])->find();
                    $detail['goods_id'] = $v['goods_id'];
                    $detail['goods_name'] = $v['goods']['name'];
                    $detail['goods_original_price'] = $v['goods']['original_price'];
                    $detail['unit'] = $unit?$unit->group_detail_name:'';
                    $detail['sku_name'] = $sku?$sku->name:null;

                }else{
                    $detail['goods_name'] = $v['goods_name'];
                    $detail['goods_original_price'] = $v['original_price'];
                    $detail['unit'] = $v['unit_name'];
                }
                $this->order_goods_group_detail[] = $detail;
            }

        }

    }

    /*订单产品信息记录*/
    protected function goods($datas,$order_id,$order_item_id){
        $order_goods = [
            'goods_id'=>$datas['goods_id'],
            'order_id'=>$order_id,
            'order_item_id'=>$order_item_id,
            'use_type'=>$datas['use_type'],
            'use_time_type'=>$datas['use_time_type'],
            'use_time_num'=>$datas['use_time_num'],
            'use_start_time'=>$datas['use_start_time'],
            'use_end_time'=>$datas['use_end_time'],
            'use_limit'=>$datas['use_limit'],
            'use_limit_detail'=>$datas['use_limit_detail'],
            'is_limit_buy'=>$datas['is_limit_buy'],
            'can_buy_type'=>$datas['can_buy_type'],
            'can_buy_num'=>$datas['can_buy_num'],
            'total_value'=>$datas['total_value'],
            'is_need_appointment'=>$datas['is_need_appointment'],
            'appointment_explain'=>$datas['appointment_explain'],
            'purchase_information'=>$datas['purchase_information'],
            'remarks'=>$datas['remarks'],
            'weight'=>$datas['weight'],
            'type'=>$datas['type'],
        ];

        $order_goods_model =new OrderGoodsModel();
        $order_goods_model->save($order_goods);
    }

    public function cancelOrder($params)

    {

        $this->checkMember($params['member_id'],false);

        $this->checkOrder($params['order_id'],true);



        if($this->order->order_type != 'flash_sale') $this->error('订单不存在');

        if($this->order->is_delete != 0) $this->error('订单不存在');

        if($this->order->is_paid == 1 || $this->order->status != 1) $this->error('订单无法取消');



        $this->order->status=-1;

        $this->order->save();



        $this->cancelGoods();



        //保存秒杀商品

        $flash_sale_goods_model=new FlashSaleGoodsModel();

        $flash_sale_goods_model->saveAll($this->flash_sale_goods_data);



        //保存商品规格

        $flash_sale_goods_sku_model = new FlashSaleGoodsSkuModel();

        $flash_sale_goods_sku_model->saveAll($this->flash_sale_sku_datas);



        return true;

    }



    public function getIntegralBalance($total_price)

    {

        $SettingBalance = SettingBalanceModel::where([['shop_id','=', $this->shopId]])->find();

        if(null === $SettingBalance){

            $integral_deduction_balance_limit_rate = 0;

        }else{

            $integral_deduction_balance_limit_rate = $SettingBalance->integral_deduction_balance_limit_rate; //积分抵扣的比率 百分比

        }

        $integralSetting = SettingIntegralModel::where([['shop_id','=', $this->shopId]])->find();

        if($integralSetting === null){ //如果是空 代表不使用积分抵扣余额

            $integral_exchange_balance = 0;

        }else{

            $integral_exchange_balance = $integralSetting->integral_exchange_balance;//汇率

        }



        $pre_can_exchange_balance=round(($total_price*($integral_deduction_balance_limit_rate*100))/10000,2);

        $pre_can_exchange_integral=$integral_exchange_balance==0 ? 0 :round(($pre_can_exchange_balance*10000)/($integral_exchange_balance*100),0);

        $member_integral=$this->member->integral;

        if($member_integral>=$pre_can_exchange_integral){

            $return=[

                'integral'=>$pre_can_exchange_integral,

                'balance'=>$pre_can_exchange_balance

            ];

        }else{

            $return=[

                'integral'=>$member_integral,

                'balance'=>round(($member_integral*($integral_exchange_balance*100))/10000,2),

            ];

        }

        return $return;



    }



    public function checkGoods($datas,$lock)

    {

        empty($datas['flash_sale_goods_id']) && $this->error('参数错误#6');

        empty($datas['num']) && $this->error('参数错误#4');

        $this->num = ($this->num ?? 0) + $datas['num'];

        $this->flash_sale_goods_id = $datas['flash_sale_goods_id'];

        $today=date("Y-m-d",time());

        $flash_sale_goods=FlashSaleGoodsModel::with(['goods'])->where([

            ['status','=',1],

            ['is_delete','=',0],

            ['flash_sale_goods_id','=',$datas['flash_sale_goods_id']],

            ['quota','>=',$datas['num']],

            ['start_time','<=',$today],

            ['end_time','>=',$today],

        ])->field('flash_sale_goods_id,goods_id,shop_id,flash_sale_price,gross,quota,take_count,fictitious_take_count,is_have_sku,use_type,use_time_type,use_time_num,use_start_time,use_end_time,is_limit_buy,limit_buy_type,limit_buy_num,is_limit_num,limit_num_type,limit_num')

            ->lock($lock)->find();

        empty($flash_sale_goods) && $this->error('请选择商品');

        $this->shopId = $flash_sale_goods->shop_id;

        $goods=GoodsModel::find($flash_sale_goods->goods_id);

        empty($goods) && $this->error('商品不存在');

        //判断限购
        if($flash_sale_goods->is_limit_buy){
            if($flash_sale_goods->limit_buy_type==1){
                //单个用户
                $return = \app\stores\model\order\GoodsOrderModel::getCount(['order_type'=>'flash_sale','shop_id'=>$this->shopId,'member_id'=>$this->member_id,'goods_id'=>$flash_sale_goods->flash_sale_goods_id,'not_status'=>[1,-1]]);
                $buy_goods_num = $return['count'];
            }else{
                //单个订单
                $buy_goods_num = $datas['num'];
            }
            if($buy_goods_num>$flash_sale_goods->limit_buy_num){
                $this->error('已超过可以购买的数量');
            }

        }
        //判断限量
        if($flash_sale_goods->is_limit_num){
            if($flash_sale_goods->limit_num_type==1){
                //每天限量
                $start_time = strtotime(date("Y-m-d",time()));
                $end_time = $start_time+60*60*24;
                $return = \app\stores\model\order\GoodsOrderModel::getCount(['order_type'=>'flash_sale','shop_id'=>$this->shopId,'goods_id'=>$flash_sale_goods->flash_sale_goods_id,'not_status'=>[1,-1],'start_time'=>$start_time,'end_time'=>$end_time]);
                $buy_goods_num = $return['count']+$datas['num'];
                if($buy_goods_num>$flash_sale_goods->limit_num){
                    $this->error('已超过限量购买的数量');
                }
            }else{
                //全部库存
                $return = \app\stores\model\order\GoodsOrderModel::getCount(['order_type'=>'flash_sale','shop_id'=>$this->shopId,'goods_id'=>$flash_sale_goods->flash_sale_goods_id,'not_status'=>[1,-1]]);
                $buy_goods_num = $return['count'];
                if($buy_goods_num>$goods->quota){
                    $this->error('已超过限量购买的数量');
                }
            }

        }else{
            //不限量判断产品库存
            if($datas['num']>$goods->quota){
                $this->error('已超过库存');
            }
        }

        //判断有效期
        $this->order_goods_data[]=[
            'goods_id'=>$flash_sale_goods->goods_id,
            'use_type'=>$flash_sale_goods->use_type,
            'use_time_type'=>$flash_sale_goods->use_time_type,
            'use_time_num'=>$flash_sale_goods->use_time_num,
            'use_start_time'=>$flash_sale_goods->use_start_time,
            'use_end_time'=>$flash_sale_goods->use_end_time,
            'is_limit_buy'=>$flash_sale_goods->is_limit_buy,
            'can_buy_type'=>$flash_sale_goods->limit_buy_type,
            'can_buy_num'=>$flash_sale_goods->limit_buy_num,
            'purchase_information'=>$flash_sale_goods->purchase_information,
            'type'=>$goods->type
        ];

        $this->goods = $goods;

       $flash_sale_goods_sku_id=isset($datas['flash_sale_goods_sku_id']) ? $datas['flash_sale_goods_sku_id'] : 0;

       if($flash_sale_goods_sku_id != 0){

           $flash_sale_sku=FlashSaleGoodsSkuModel::where([

               ['shop_id','=',$this->shopId],

               ['is_delete','=',0],

               ['flash_sale_goods_id','=',$datas['flash_sale_goods_id']],

               ['flash_sale_goods_sku_id','=',$flash_sale_goods_sku_id],

               ['quota','>=',$datas['num']]

           ])->field('flash_sale_goods_sku_id,name,original_price,flash_sale_price,quota,take_count,gross')

               ->lock($lock)->find();

           if(null === $flash_sale_sku) $this->error($goods->name.'的规格缺货');


       }

        //分类
        $category = GoodsCategoryModel::where(['shop_id'=>$goods['shop_id'],'category_id'=>$goods['category_id'],'is_delete'=>0])->find();

        //处理订单商品表

        $this->order_item_data[]=[

            'shop_id'=>$this->shopId,

            'goods_id'=>$datas['flash_sale_goods_id'],

            'goods_type'=>'flash_sale',

            'category_name'=>$category?$category->name:null,

            'goods_name'=>$goods->name,

            'goods_gross'=>($flash_sale_goods_sku_id != 0)?$flash_sale_sku->gross:$flash_sale_goods->gross,

            'goods_cover_img'=>$goods->cover_img,

            'goods_sku_id'=>$flash_sale_goods_sku_id,

            'goods_sku_name'=>isset($flash_sale_sku) ? $flash_sale_sku->name : '',

            'goods_original_price'=>isset($flash_sale_sku) ? $flash_sale_sku->original_price : $goods->original_price,

            'goods_price'=>isset($flash_sale_sku) ? $flash_sale_sku->flash_sale_price : $flash_sale_goods->flash_sale_price,

            'goods_num'=>$datas['num'],

            'type'=>$flash_sale_goods->goods->type,

            'add_time'=>request()->time(),

            'add_ip'=> request()->ip()

        ];



        $price=isset($flash_sale_sku) ?  $flash_sale_sku->flash_sale_price :  $flash_sale_goods->flash_sale_price;

        $this->total_price=round((($this->total_price)*100+$price*$datas['num']*100)/100,2);

        $this->all_goods_gross += ($flash_sale_goods_sku_id != 0)?$flash_sale_sku->gross*$datas['num']:$flash_sale_goods->gross*$datas['num'];

       //处理秒杀商品表

        $flash_sale_goods=$flash_sale_goods->toArray();

        $flash_sale_goods['quota']=$flash_sale_goods['quota']-$datas['num'];

        $flash_sale_goods['take_count']=$flash_sale_goods['take_count']+$datas['num'];

        $flash_sale_goods['fictitious_take_count']=$flash_sale_goods['fictitious_take_count']+$datas['num'];

        $this->flash_sale_goods_data[]=$flash_sale_goods;



       //处理规格表

        if(isset($flash_sale_sku)){

            $flash_sale_sku=$flash_sale_sku->toArray();

            $flash_sale_sku['quota']=$flash_sale_sku['quota']-$datas['num'];

            $flash_sale_sku['take_count']=$flash_sale_sku['take_count']+$datas['num'];

            $this->flash_sale_sku_datas[]=$flash_sale_sku;

        }



    }



    protected function cancelGoods()

    {

        $order_item_data=GoodsOrderItemModel::where([

            ['shop_id','=',$this->shopId],

            ['order_id','=',$this->order->order_id],

            ['goods_type','=','falsh_sale']

        ])->field('goods_id,goods_sku_id,goods_num')->select()->toArray();

        $goods_ids=[];$sku_ids=[];$order_item_array=[];



        if(!empty($order_item_data)){

            foreach ($order_item_data as $k => $v){

                $goods_ids[]=$v['goods_id'];

                $sku_ids[]=$v['goods_sku_id'];

                $order_item_array['goods'][$v['goods_id']]=$v;

                $order_item_array['sku'][$v['goods_sku_id']]=$v;

            }

        }



        //处理秒杀商品

        $flash_sale_goods_data=FlashSaleGoodsModel::where([

            ['shop_id','=',$this->shopId],

            ['flash_sale_goods_id','IN',$goods_ids],

        ])->field('flash_sale_goods_id,quota,take_count,fictitious_take_count')->select()->toArray();



        foreach ($flash_sale_goods_data as $k => $v){

            $num=$order_item_array['goods'][$v['flash_sale_goods_id']]['goods_num'] ?? 0;

            $flash_sale_goods_data[$k]['quota']=$v['quota'] +$num;

            $flash_sale_goods_data[$k]['fictitious_take_count']=($v['fictitious_take_count'] -$num) <=0 ? $v['fictitious_take_count'] : ($v['fictitious_take_count'] -$num);

            $flash_sale_goods_data[$k]['take_count']=$v['take_count'] -$num;

        }

        $this->flash_sale_goods_data=$flash_sale_goods_data;



        //处理规格

        $flash_sale_sku_datas=FlashSaleGoodsSkuModel::where([

            ['shop_id','=',$this->shopId],

            ['flash_sale_goods_sku_id','IN',$sku_ids],

        ])->field('flash_sale_goods_sku_id,quota,take_count')->select()->toArray();



        foreach ($flash_sale_sku_datas as $k => $v){

            $num=$order_item_array['sku'][$v['flash_sale_goods_sku_id']]['goods_num'] ?? 0;

            $flash_sale_sku_datas[$k]['quota']=$v['quota'] +$num;

            $flash_sale_sku_datas[$k]['take_count']=$v['take_count'] -$num;

        }

        $this->flash_sale_sku_datas=$flash_sale_sku_datas;

    }

}